#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ini.h"
#include "register.h"
#include "common.h"

int section_count = 0;

static void register_section(const char* name, void* data, SectionHandlerTwo handler2, SectionHandlerThree handler3) 
{
    if (section_count < MAX_SECTIONS) {
        sections[section_count].name = name;
        sections[section_count].data = data;
        if (handler2 != NULL) {
            sections[section_count].handler2 = handler2;
        } else if (handler3 != NULL) {
            sections[section_count].handler3 = handler3;
        }
        section_count++;
    } else {
        printf("Error: Too many sections!\n");
    }
}

void fillSection1Info(const char* name, const char* value, void* data)
{
    Section1Data* section1_data = (Section1Data*)data;
    if (strcmp(name, "key1") == 0) {
        strncpy(section1_data->key1, value, sizeof(section1_data->key1));
    } else if (strcmp(name, "key2") == 0) {
        section1_data->key2 = atoi(value);
    }
}

// ini文件的回调函数
static int handler(void* user, const char* section, const char* name, const char* value) {
    for (int i = 0; i < section_count; i++) {
        if (strcmp(section, sections[i].name) == 0) {
            if (strcmp(section, "baseInfo") == 0) {
                fillBaseInfo(name, value);
            } else if (strcmp(section, "section0") == 0) {
                // do nothing
            } else if (strcmp(section, "section1") == 0) {
                fillSection1Info(name, value, sections[i].data);
            } else if (strcmp(section, "section2") == 0) {
                parse_hex_string(value, sections[i].data, sizeof(Section2Data));
            }
            break;
        }
    }
    return 1; // 返回1表示成功处理
}

int main() {

    register_section("section0", NULL, process_section0, NULL);
    
    Section1Data section1_data = { 0 };
    register_section("section1", &section1_data, NULL, process_section1);
    
    Section2Data section2_data = { 0 };
    register_section("section2", &section2_data, NULL, process_section2);

    // 读取ini文件
    if (ini_parse("config.ini", handler, NULL) < 0) {
        printf("Error: Cannot load 'config.ini'\n");
        return 1;
    }

    int ep = getEp(devName);
    // 调用每个section的处理函数
    for (int i = 0; i < section_count; i++) {
        if (sections[i].handler2 != NULL) {
            sections[i].handler2(&ep, &cxlBaseInfo);
        } else if (sections[i].handler3 != NULL) {
            sections[i].handler3(&ep, &cxlBaseInfo, sections[i].data);
        }
    }
    return 0;
}